<template>
	<view class="order-management-container">
		<!-- 顶部导航栏 -->
		<view class="custom-nav-bar">
			<view class="nav-back-btn" @click="goBack">
				<uni-icons type="arrowleft" size="24" color="#fff"></uni-icons>
			</view>
			<text class="nav-title">零食订单管理系统</text>
		</view>

		<!-- 订单状态分类 -->
		<view class="order-status-tabs">
			<view 
				class="status-tab" 
				:class="{active: activeTab === 0}"
				@click="activeTab = 0"
			>
				<text>全部订单</text>
				<view class="tab-indicator" v-if="activeTab === 0"></view>
			</view>
			<view 
				class="status-tab" 
				:class="{active: activeTab === 1}"
				@click="activeTab = 1"
			>
				<text>新订单</text>
				<view class="tab-indicator" v-if="activeTab === 1"></view>
			</view>
			<view 
				class="status-tab" 
				:class="{active: activeTab === 2}"
				@click="activeTab = 2"
			>
				<text>已完成</text>
				<view class="tab-indicator" v-if="activeTab === 2"></view>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list-container" scroll-y>
			<!-- 新订单部分 -->
			<view class="order-section" v-if="activeTab === 0 || activeTab === 1">
				<view class="section-header">
					<text class="section-title">新订单</text>
					<text class="order-count">({{newOrderGroups.length}})</text>
				</view>
				
				<view class="order-card-wrapper" v-for="(group, index) in newOrderGroups" :key="'new-'+index">
					<view class="order-card" @click="viewStudentOrders(group.studentId, group.studentName)">
						<!-- 订单头部 -->
						<view class="order-header">
							<view class="student-info">
								<view class="student-avatar" :style="{background: getAvatarGradient(group.studentName)}">
									<text class="avatar-text">{{getFirstChar(group.studentName)}}</text>
								</view>
								<view class="student-details">
									<text class="student-name">{{group.studentName}}</text>
									<text class="order-time">{{formatDisplayTime(group.createTime)}}</text>
								</view>
							</view>
							<view class="order-status new">
								<text>待处理</text>
								<view class="status-indicator"></view>
							</view>
						</view>
						
						<!-- 订单内容 -->
						<view class="order-body">
							<!-- 商品列表 -->
							<view class="product-items">
								<view class="product-item" v-for="(item, i) in group.items" :key="i">
									<image class="product-img" :src="getImageUrl(item.snackImage)" mode="aspectFill"></image>
									<view class="product-details">
										<text class="product-name">{{item.snackName}}</text>
										<view class="price-quantity">
											<text class="product-price">¥{{item.price.toFixed(2)}}</text>
											<text class="product-qty">×{{item.quantity || 1}}</text>
										</view>
									</view>
								</view>
							</view>
							
							<!-- 订单详情 -->
							<view class="order-meta">
								<view class="meta-row">
									<uni-icons type="location-filled" size="16" color="#9E9E9E"></uni-icons>
									<text class="meta-text">送货地址: {{getDeliveryAddress(group.studentName)}}</text>
								</view>
								<view class="meta-row">
									<uni-icons type="time-filled" size="16" color="#9E9E9E"></uni-icons>
									<text class="meta-text">下单时间: {{formatDetailTime(group.createTime)}}</text>
								</view>
							</view>
						</view>
						
						<!-- 订单底部 -->
						<view class="order-footer">
							<text class="items-count">共{{calculateTotalQuantity(group.items)}}件商品</text>
							<text class="total-price">合计: ¥{{calculateTotalAmount(group.items)}}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 已完成订单 -->
			<view class="order-section" v-if="activeTab === 0 || activeTab === 2">
				<view class="section-header">
					<text class="section-title">已完成</text>
					<text class="order-count">({{completedOrderGroups.length}})</text>
				</view>
				
				<view class="order-card-wrapper" v-for="(group, index) in completedOrderGroups" :key="'completed-'+index">
					<view class="order-card" @click="viewStudentOrders(group.studentId, group.studentName)">
						<!-- 订单头部 -->
						<view class="order-header">
							<view class="student-info">
								<view class="student-avatar" :style="{background: getAvatarGradient(group.studentName)}">
									<text class="avatar-text">{{getFirstChar(group.studentName)}}</text>
								</view>
								<view class="student-details">
									<text class="student-name">{{group.studentName}}</text>
									<text class="order-time">{{formatDisplayTime(group.createTime)}}</text>
								</view>
							</view>
							<view class="order-status completed">
								<text>已完成</text>
								<view class="status-indicator"></view>
							</view>
						</view>
						
						<!-- 订单内容 -->
						<view class="order-body">
							<!-- 商品列表 -->
							<view class="product-items">
								<view class="product-item" v-for="(item, i) in group.items" :key="i">
									<image class="product-img" :src="getImageUrl(item.snackImage)" mode="aspectFill"></image>
									<view class="product-details">
										<text class="product-name">{{item.snackName}}</text>
										<view class="price-quantity">
											<text class="product-price">¥{{item.price.toFixed(2)}}</text>
											<text class="product-qty">×{{item.quantity || 1}}</text>
										</view>
									</view>
								</view>
							</view>
							
							<!-- 订单详情 -->
							<view class="order-meta">
								<view class="meta-row">
									<uni-icons type="location-filled" size="16" color="#9E9E9E"></uni-icons>
									<text class="meta-text">送货地址: {{getDeliveryAddress(group.studentName)}}</text>
								</view>
								<view class="meta-row">
									<uni-icons type="time-filled" size="16" color="#9E9E9E"></uni-icons>
									<text class="meta-text">下单时间: {{formatDetailTime(group.createTime)}}</text>
								</view>
								<view class="meta-row">
									<uni-icons type="checkmark-filled" size="16" color="#9E9E9E"></uni-icons>
									<text class="meta-text">完成时间: {{formatDetailTime(group.updateTime)}}</text>
								</view>
							</view>
						</view>
						
						<!-- 订单底部 -->
						<view class="order-footer">
							<text class="items-count">共{{calculateTotalQuantity(group.items)}}件商品</text>
							<text class="total-price">合计: ¥{{calculateTotalAmount(group.items)}}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态提示 -->
			<view class="empty-state" v-if="showEmptyTip">
				<image class="empty-icon" src="/static/empty-order.png" mode="aspectFit"></image>
				<text class="empty-message">暂无相关订单</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				orders: [],
				loading: false,
				activeTab: 1, // 默认显示新订单
				specialStudents: ['张玉欣', '张富豪', '徐晔涵', '侯新意', '吴晟睿', '张金坤', '张恩豫']
			}
		},
		
		computed: {
			// 分组合并订单
			groupedOrders() {
				const groups = {};
				const TIME_GROUP_INTERVAL = 10000; // 10秒内视为同一订单
				
				// 按学生和时间分组
				this.orders.forEach(order => {
					const timeKey = Math.floor(new Date(order.createdAt).getTime() / TIME_GROUP_INTERVAL) * TIME_GROUP_INTERVAL;
					const groupKey = `${order.studentId}-${timeKey}`;
					
					if (!groups[groupKey]) {
						groups[groupKey] = {
							studentId: order.studentId,
							studentName: order.studentName,
							createTime: order.createdAt,
							updateTime: order.updatedAt,
							paymentStatus: order.paymentStatus,
							items: []
						};
					}
					groups[groupKey].items.push(order);
				});
				
				// 合并相同商品
				const mergedGroups = [];
				Object.values(groups).forEach(group => {
					const snackMap = {};
					group.items.forEach(item => {
						if (!snackMap[item.snackId]) {
							snackMap[item.snackId] = {
								...item,
								quantity: 1,
								originalIds: [item.id]
							};
						} else {
							snackMap[item.snackId].quantity += 1;
							snackMap[item.snackId].originalIds.push(item.id);
						}
					});
					
					mergedGroups.push({
						...group,
						items: Object.values(snackMap)
					});
				});
				
				// 按时间倒序排序
				return mergedGroups.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
			},
			
			// 新订单组
			newOrderGroups() {
				return this.groupedOrders.filter(group => group.paymentStatus === 0);
			},
			
			// 已完成订单组
			completedOrderGroups() {
				return this.groupedOrders.filter(group => group.paymentStatus === 1);
			},
			
			// 是否显示空状态
			showEmptyTip() {
				if (this.loading) return false;
				if (this.activeTab === 0 && this.groupedOrders.length === 0) return true;
				if (this.activeTab === 1 && this.newOrderGroups.length === 0) return true;
				if (this.activeTab === 2 && this.completedOrderGroups.length === 0) return true;
				return false;
			}
		},
		
		onLoad() {
			this.fetchOrders();
		},
		
		methods: {
			// 获取订单数据
			async fetchOrders() {
				this.loading = true;
				try {
					const res = await uni.request({
						url: `${globalVariable}/getAllSnackOrders`,
						method: 'GET'
					});
					
					if (res.data && res.data.status === 1) {
						this.orders = res.data.data || [];
					} else {
						uni.showToast({
							title: res.data.message || '获取订单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取订单失败:', error);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 获取图片URL
			getImageUrl(url) {
				if (!url) return '/static/default-product.png';
				if (url.startsWith('http')) return url;
				return `${globalVariable}/getSnackImage/${url}`;
			},
			
			// 获取头像渐变背景
			getAvatarGradient(name) {
				const colors = [
					'linear-gradient(135deg, #4a8fe7, #6ba8ff)',
					'linear-gradient(135deg, #07c160, #5cb87a)',
					'linear-gradient(135deg, #ff976a, #ff6b6b)',
					'linear-gradient(135deg, #9c27b0, #e91e63)',
					'linear-gradient(135deg, #00bcd4, #009688)',
					'linear-gradient(135deg, #ff9800, #ff5722)',
					'linear-gradient(135deg, #673ab7, #3f51b5)'
				];
				const index = name ? name.charCodeAt(0) % colors.length : 0;
				return colors[index];
			},
			
			// 获取名字首字母
			getFirstChar(name) {
				return name ? name.charAt(0).toUpperCase() : '?';
			},
			
			// 获取送货地址
			getDeliveryAddress(studentName) {
				return this.specialStudents.includes(studentName) ? '高一年级' : '大辛辅导班';
			},
			
			// 格式化显示时间（简洁）
			formatDisplayTime(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				const now = new Date();
				
				// 如果是今天
				if (date.toDateString() === now.toDateString()) {
					return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
				}
				
				// 如果是昨天
				const yesterday = new Date(now);
				yesterday.setDate(yesterday.getDate() - 1);
				if (date.toDateString() === yesterday.toDateString()) {
					return '昨天';
				}
				
				// 其他情况显示月-日
				return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			},
			
			// 格式化详情时间（完整）
			formatDetailTime(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
			},
			
			// 计算订单总金额
			calculateTotalAmount(items) {
				return items.reduce((total, item) => total + (item.price * (item.quantity || 1)), 0).toFixed(2);
			},
			
			// 计算商品总数量
			calculateTotalQuantity(items) {
				return items.reduce((total, item) => total + (item.quantity || 1), 0);
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 查看学生订单详情
			viewStudentOrders(studentId, studentName) {
				uni.navigateTo({
					url: `/pages/snackOrderDetail/snackOrderDetail?studentId=${studentId}&studentName=${studentName}`
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	*{
		box-sizing: border-box;
	}
	.order-management-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}
	
	.custom-nav-bar {
		display: flex;
		align-items: center;
		padding: 15px 20px;
		background: linear-gradient(135deg, #4a8fe7, #6ba8ff);
		color: white;
		position: relative;
		box-shadow: 0 2px 10px rgba(74, 143, 231, 0.2);
		
		.nav-back-btn {
			width: 24px;
			height: 24px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.nav-title {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			font-size: 18px;
			font-weight: 600;
			letter-spacing: 0.5px;
		}
	}
	
	.order-status-tabs {
		display: flex;
		background-color: #fff;
		padding: 0 15px;
		border-bottom: 1px solid #f0f0f0;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}
	
	.status-tab {
		flex: 1;
		text-align: center;
		padding: 16px 0;
		font-size: 15px;
		color: #666;
		position: relative;
		font-weight: 500;
		transition: all 0.3s ease;
		
		&.active {
			color: #4a8fe7;
			font-weight: 600;
		}
	}
	
	.tab-indicator {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40px;
		height: 3px;
		background-color: #4a8fe7;
		border-radius: 3px;
	}
	
	.order-list-container {
		flex: 1;
		padding: 15px;
		padding-bottom: 80px;
	}
	
	.order-section {
		margin-bottom: 25px;
	}
	
	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 16px;
		padding-left: 8px;
	}
	
	.section-title {
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}
	
	.order-count {
		font-size: 14px;
		color: #999;
		margin-left: 6px;
	}
	
	.order-card-wrapper {
		margin-bottom: 16px;
	}
	
	.order-card {
		background-color: #fff;
		border-radius: 16px;
		overflow: hidden;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
		
		&:active {
			transform: translateY(2px);
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
		}
	}
	
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px;
		background-color: #f8fafc;
		border-bottom: 1px solid #f1f5f9;
	}
	
	.student-info {
		display: flex;
		align-items: center;
	}
	
	.student-avatar {
		width: 44px;
		height: 44px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 12px;
		box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
		
		.avatar-text {
			color: white;
			font-size: 18px;
			font-weight: 600;
		}
	}
	
	.student-details {
		display: flex;
		flex-direction: column;
	}
	
	.student-name {
		font-size: 16px;
		font-weight: 600;
		color: #2c3e50;
		margin-bottom: 4px;
		letter-spacing: 0.3px;
	}
	
	.order-time {
		font-size: 12px;
		color: #7f8c8d;
		font-weight: 400;
	}
	
	.order-status {
		display: flex;
		align-items: center;
		padding: 6px 12px;
		border-radius: 16px;
		font-size: 13px;
		font-weight: 500;
		
		&.new {
			color: #ff6b6b;
			background-color: rgba(255, 107, 107, 0.1);
		}
		
		&.completed {
			color: #07c160;
			background-color: rgba(7, 193, 96, 0.1);
		}
	}
	
	.status-indicator {
		width: 6px;
		height: 6px;
		border-radius: 50%;
		margin-left: 6px;
		
		.new & {
			background-color: #ff6b6b;
			animation: pulse 1.5s infinite;
		}
		
		.completed & {
			background-color: #07c160;
		}
	}
	
	.order-body {
		padding: 16px;
	}
	
	.product-items {
		margin-bottom: 12px;
	}
	
	.product-item {
		display: flex;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px dashed #f1f5f9;
		
		&:last-child {
			border-bottom: none;
		}
	}
	
	.product-img {
		width: 56px;
		height: 56px;
		border-radius: 8px;
		object-fit: cover;
		background-color: #f8fafc;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
	}
	
	.product-details {
		flex: 1;
		margin-left: 14px;
	}
	
	.product-name {
		font-size: 15px;
		font-weight: 500;
		color: #34495e;
		margin-bottom: 6px;
		letter-spacing: 0.3px;
	}
	
	.price-quantity {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.product-price {
		font-size: 15px;
		color: #ff6b6b;
		font-weight: 600;
	}
	
	.product-qty {
		font-size: 14px;
		color: #95a5a6;
	}
	
	.order-meta {
		margin-top: 16px;
		padding: 12px;
		background-color: #f8fafc;
		border-radius: 10px;
	}
	
	.meta-row {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
		
		&:last-child {
			margin-bottom: 0;
		}
	}
	
	.meta-text {
		font-size: 14px;
		color: #7f8c8d;
		margin-left: 8px;
	}
	
	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 14px 16px;
		background-color: #f8fafc;
		border-top: 1px solid #f1f5f9;
	}
	
	.items-count {
		font-size: 14px;
		color: #7f8c8d;
	}
	
	.total-price {
		font-size: 16px;
		font-weight: 700;
		color: #4a8fe7;
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 0;
	}
	
	.empty-icon {
		width: 120px;
		height: 120px;
		margin-bottom: 15px;
		opacity: 0.5;
	}
	
	.empty-message {
		font-size: 15px;
		color: #999;
	}
	
	@keyframes pulse {
		0% {
			transform: scale(0.95);
			opacity: 0.7;
		}
		70% {
			transform: scale(1.2);
			opacity: 1;
		}
		100% {
			transform: scale(0.95);
			opacity: 0.7;
		}
	}
</style>